//
//  LoginViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "LoginViewController.h"
#import "Common.h"
#import <Masonry/Masonry.h>
#import "ForgetpasswordViewController.h"
#import "RegisterViewController.h"
#import "WKProgressHUD.h"
#import "RootViewController.h"
#import "SSKeychain.h"
#import "Header.h"
#define leftMar 60

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneTextField;

@property (nonatomic, strong) UITextField *captchaTextField;

@property (nonatomic, strong) UIButton *captchaButton;

@property (nonatomic, assign) int secondCountDown;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, copy) NSString *uuidString;

@end

@implementation LoginViewController

#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView) {
           _topBackView = [[TopBackView alloc] initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"慧运车"];
        _topBackView.leftButton.hidden = YES;
        _topBackView.rightButton.hidden = YES;
    }
    return _topBackView;
}
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
        _scrollView.contentSize = CGSizeMake(screenWidth, screenHeight);
        _scrollView.backgroundColor = WhiteColor;

        _scrollView.scrollEnabled = NO;
    }
    return _scrollView;
}


#pragma mark -
#pragma mark - 控制器初始化
- (void)viewDidLoad {
    [super viewDidLoad];
  
    ///设置UI
    [self setUpUI];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}


#pragma mark -
#pragma mark - 设置UI
- (void)setUpUI {
    
    self.view.backgroundColor = WhiteColor;
    
    ///添加自定义导航栏
//    [self.view addSubview:self.topBackView];
    
    ///添加滚动视图
    [self.view addSubview:self.scrollView];
    
    [self initSubviews];
}
- (void)initSubviews {
    
  
    
    UIImageView * backImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login"]];
    backImage.frame =CGRectMake(0, -20, Main_Width, Main_height);
    [self.scrollView addSubview:backImage];
    
    
    
    ///顶部Logo
    UIImageView *logoImageV = [[UIImageView alloc]initWithFrame:CGRectMake((screenWidth - 108)/2.0, 55 * kHeight, 108, 40)];
    logoImageV.image = [UIImage imageNamed:@"register_logo"];
//    [self.scrollView addSubview:logoImageV];
    
    //输入框
    self.phoneTextField = [[UITextField alloc]init];

    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneTextField.textColor = WhiteColor;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = UITextColor;
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:self.phoneTextField.placeholder attributes:dict];
    [self.phoneTextField setAttributedPlaceholder:attribute];
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入6-14位密码";
    self.captchaTextField.textColor = WhiteColor;
    self.captchaTextField.secureTextEntry = YES;
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    NSAttributedString *attribute1 = [[NSAttributedString alloc] initWithString:self.captchaTextField.placeholder attributes:dict];
    [self.captchaTextField setAttributedPlaceholder:attribute1];

    //手机号
    UIView *firstV = [self
                      backViewWithFloat:(200 *kHeight)
                      andField:self.phoneTextField
                      andImage:[UIImage imageNamed:@"register_password"]];
    [self.scrollView addSubview:firstV];
    
    //密码
    UIView *secondV = [self
                       backViewWithFloat:CGRectGetMaxY(firstV.frame)
                       andField:self.captchaTextField
                       andImage:[UIImage imageNamed:@"register_phone"]];
    [self.scrollView addSubview:secondV];
    
    
    ///登录
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake( 18,CGRectGetMaxY(secondV.frame) + 30 *kHeight, screenWidth - 36, 35 * kHeight);
    loginButton.backgroundColor = YellowColor ;
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    loginButton.layer.cornerRadius = 5;
    loginButton.titleLabel.font = Font(15);
    [self.scrollView addSubview:loginButton];
    [loginButton addTarget:self
                    action:@selector(LoginButtonAction)
          forControlEvents:UIControlEventTouchUpInside];
    
    ///忘记密码
    UIButton *forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetButton.frame = CGRectMake(CGRectGetMaxX(loginButton.frame)-110, CGRectGetMaxY(loginButton.frame) + 15, 110, 20);
    [forgetButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetButton setTitleColor:YellowColor forState:UIControlStateNormal];
    forgetButton.titleLabel.font = Font(13);
    [self.scrollView addSubview:forgetButton];
    [forgetButton addTarget:self
                     action:@selector(forgetButton)
           forControlEvents:UIControlEventTouchUpInside];
    
    /*
    ///注册
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.frame = CGRectMake(screenWidth - 20 - 40,  CGRectGetMaxY(loginButton.frame) + 15, 40, 20);
    [registerButton setTitleColor:YellowColor forState:UIControlStateNormal];
    [registerButton setTitle:@"注册" forState:UIControlStateNormal];
    registerButton.titleLabel.font = Font(13);
    [registerButton addTarget:self
                       action:@selector(registerButtonAction)
             forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:registerButton];
    */
}


#pragma mark 忘记密码 - 推出忘记密码Vc
- (void)forgetButton{
    
    ForgetpasswordViewController *forgetVC = [[ForgetpasswordViewController alloc]init];
   
    [self.navigationController pushViewController:forgetVC animated:YES];
}


#pragma mark 协议方法
-(void)protocolButton {
    
}


#pragma mark 登录方法
-(void)LoginButtonAction{

    
    //保存为已经进入app
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstIn"];
    [[NSUserDefaults standardUserDefaults]synchronize];//及时保存 不等到按home键就保存内容
    
    
    if (self.callBack) {
        _callBack();
    };

    
      //获取uuid
      [self sendUUID];
    
//      NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

//      NSString *pushid = [NSString stringWithFormat:@"%@",[userDefaults objectForKey:@"pushid"]];
    
//      NSString *deviceName = [[UIDevice currentDevice] systemName];
    
      NSDictionary *dic = @{@"loginName" : self.phoneTextField.text,
                            @"pwd": self.captchaTextField.text};
      
      NSArray *arr = [dic allValues];
      
      if ([arr containsObject:@""])
      {
          [WKProgressHUD popMessage:@"请将信息补充完整"
                             inView:self.view
                           duration:1.5
                           animated:YES];
          
          return;
      }
    
    __weak typeof(self) weakSelf = self;

    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
   
    NSLog(@"%@",login_codeLogin);
    NSString * url = [NSString stringWithFormat:@"%@/%@/%@",login_codeLogin,dic[@"loginName"],dic[@"pwd"]];
    [[Common shared] afPostRequestWithUrlString:url parms:nil finishedBlock:^(id responseObj) {
      
      [WKProgressHUD dismissInView:weakSelf.view animated:YES];

       NSDictionary *dictonary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
      
      [WKProgressHUD popMessage:dictonary[@"message"] inView:weakSelf.view duration:1.5 animated:YES];
      
      if ([[dictonary objectForKey:@"success"] boolValue]) {

          //登陆token
          NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//
          [userDefaults setObject:@"login" forKey:@"login"];
          [userDefaults setObject:dictonary[@"data"][@"Authorization"] forKey:login_token];
          
          //修改支付密码使用
          [userDefaults setObject:weakSelf.phoneTextField.text forKey:@"phone"];
        
          //判断用户类型
          [userDefaults setObject:dictonary[@"data"][@"userType"] forKey:@"userType"];
        
          //[userDefaults setObject:@"60" forKey:@"userType"];
          
          //写入userdefaults 确定只走一次 退出登录的时候不用走

          //注册通知  首页刷新页面
          [[NSNotificationCenter defaultCenter] postNotificationName:@"creatViews" object:nil];
          
          [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:weakSelf];

       
          [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
//              //延迟执行
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
                         
          dispatch_get_main_queue(), ^{
              
             
//              [weakSelf dismissViewControllerAnimated:YES completion:^{
//                  [[NSNotificationCenter defaultCenter] postNotificationName:@"dismiss" object:weakSelf];
//                  
//              }];
//              [weakSelf.navigationController popViewControllerAnimated:YES];
//
              
              //保存为已经进入app
              [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstIn"];
              [[NSUserDefaults standardUserDefaults]synchronize];//及时保存 不等到按home键就保存内容
              
              
              if (self.callBack) {
                  _callBack();
              }else{
                  [self.navigationController dismissViewControllerAnimated:YES completion:nil];
              };

          });
      }
      
      
  } failedBlock:^(NSString *errorMsg) {
      [WKProgressHUD dismissInView:weakSelf.view animated:YES];
      NSLog(@"%@",errorMsg);
  }];
//
    
     

  }


- (UIView *)backViewWithFloat:(CGFloat)y
                    andField:(UITextField *)textField
                    andImage:(UIImage *)image{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(29 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 100, cellHeight);
    textField.font = Font(15);
    [view addSubview:textField];
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;

    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, cellHeight - 0.5, screenWidth - 40, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}

#pragma mark -
#pragma mark - UITextField协议
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == self.captchaTextField) {
        
        [UIView animateWithDuration:0.3 animations:^{
            /* 计算偏移量 */
            
            CGFloat height = 216;
    
            UIButton *button = (UIButton *)[self.view viewWithTag:400];
            
            CGFloat offsetHeight = CGRectGetMaxY(button.frame) - (Main_height - height - 64);
            
            if (offsetHeight > 0)
            {
                self.scrollView.contentInset = UIEdgeInsetsMake(-offsetHeight , 0, 0, 0);
            }

        } completion:nil];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.2 animations:^{
        self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }];
}


#pragma mark -
#pragma mark - 获取UUID
- (void)sendUUID{
    
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"])
    {
        //查看本地是否存储指定 serviceName 和 account 的密码
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"account:@"user"];
       
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user" ];
        
        //NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
    }
    else
    {
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        self.uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }
}



#pragma mark -
#pragma mark - 弃用方法
/**
 退出注册Vc
 */
-(void)registerButtonAction{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    
    [self.navigationController pushViewController:registerVC animated:YES];
}

/**
 @param title 按标题
 @param integer 字体
 @param frame
 @return Btn
 */
- (UIButton *)backButtonWithString:(NSString *)title
                          andFont:(NSInteger)integer

                          andFrame:(CGRect)frame {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:title];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:strRange];  //设置颜色
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    
    [button setAttributedTitle:str forState:UIControlStateNormal];
    
    return button;
}

- (void)dismissSelf{
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    if ([self.backToFirst isEqualToString:@"1"]) {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
            UIButton *btn = (UIButton *)[rootVC.view viewWithTag:1001];
            [rootVC pressButton:btn];
        }];
        
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

@end
